<template>
  <el-drawer
    title="课程报名"
    :close-on-click-modal="modalDialog"
    :close-on-press-escape="modalDialog"
    :visible.sync="showApplication"
    size="600px"
    @close="closeDrawer"
  >
    <el-form ref="bmForm" :model="bmForm" :rules="rules" label-width="100px" label-suffix="：">
      <el-form-item label="课程名称" prop="courseId">
        <el-select v-model="bmForm.courseId" filterable placeholder="请选择课程名称" style="width: 100%;" @change="getreserveClassInfoPC">
          <el-option
            v-for="item in kcList"
            :key="item.courseId"
            :label="item.courseName"
            :value="item.courseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户信息" prop="memberId">
        <div>
          <MemberSearch ref="memberSearchRef" @clear="tgMemberClear" @select="tgMemberSelect" />
        </div>
      </el-form-item>
      <el-form-item v-if="tgMemberInfo.id" label="学员信息" prop="members">
        <div style="display: flex;">
          <el-select v-model="bmForm.members" multiple filterable placeholder="请选择学员" style="flex: 1;" @change="getreserveClassInfoPC">
            <el-option
              v-for="item in members"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button
            class="ml20"
            type="primary"
            @click="showAddBtn"
          >新增</el-button>
        </div>
      </el-form-item>
      <el-form-item v-if="tgMemberInfo.id && showAdd" label="新增学员" prop="name">
        <div style="display: flex;">
          <el-input
            v-model="xyForm.name"
            placeholder="请输入学员姓名"
            style="flex: 1;"
          />
          <el-select v-model="xyForm.sex" class="ml20" placeholder="请选择性别" style="flex: 1;">
            <el-option
              v-for="item in sexList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            class="ml20"
            type="primary"
            @click="sideBtn"
          >保存学员</el-button>
        </div>
      </el-form-item>
      <el-form-item v-if="pdSj" label="预约日期">
        <el-date-picker
          v-model="bmForm.day"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约日期"
          style="width: 100%"
          :picker-options="pickerOptions"
          @change="getreserveClassInfoPC"
        />
      </el-form-item>
      <template v-if="pdSj">
        <el-form-item label="教练" prop="teacherId">
          <el-select v-model="bmForm.teacherId" placeholder="请选择教练" style="width: 100%;" filterable @change="getreserveClassInfoPC">
            <el-option
              v-for="item in teachList"
              :key="item.teacherId"
              :label="item.teacherName"
              :value="item.teacherId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可约时段" prop="time">
          <el-select v-model="bmForm.time" multiple placeholder="请选择教练可约时段" style="width: 100%;" @change="getreserveClassInfoPC">
            <el-option
              v-for="(item, index) in timeList"
              :key="index"
              :label="item.startTime + '~' + item.endTime"
              :disabled="item.status=='0'"
              :value="index"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item label="课程价格" prop="price">
        <el-input
          v-model="bmForm.price"
          disabled
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="closeDrawer">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="confirmAction">去支付</el-button>
      </el-form-item>
    </el-form>
    <orderDialog v-if="isShowOrder" ref="orderRef" @studentAddSuccess="showApplication = false" @orderSuccess="showApplication = false, isShowOrder = false" />
  </el-drawer>
</template>

<script>
import {
  teacherGmList, publishCourseList, studentListByMember, studentAdd, reserveClassInfoPC
} from '@/api'
import store from '@/store'
import orderDialog from '@/components/order'
import MemberSearch from '@/components/MemberSearch'
import dayjs from 'dayjs'
export default {
  components: {
    orderDialog,
    MemberSearch
  },
  data() {
    return {
      showApplication: false,
      isShowOrder: false,
      subLoading: false,
      modalDialog: store.getters.dialog,
      bmForm: {},
      tgMemberInfo: {},
      kcList: [],
      members: [],
      teachList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      sexList: [
        { value: '0', label: '保密' },
        { value: '1', label: '男' },
        { value: '2', label: '女' }
      ],
      xyForm: {},
      timeList: [],
      pdSj: false,
      rules: {
        courseId: [{ required: true, message: '请选择课程名称', trigger: 'change' }],
        members: [{ required: true, message: '请选择学员', trigger: 'change' }],
        day: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
        time: [{ required: true, message: '请选择教练可约时段', trigger: 'change' }],
        teacherId: [{ required: true, message: '请选择教练', trigger: 'change' }],
        memberId: [{ required: true, message: '请选择会员', trigger: 'change' }]
      },
      showAdd: false
    }
  },
  created() {

  },
  methods: {
    showClick() {
      this.showApplication = true
      this.showAdd = false
      this.xyForm = {}
      this.bmForm = {
        day: dayjs(new Date()).format('YYYY-MM-DD')
      }
      this.tgMemberInfo = {}
      this.members = []
      this.pdSj = false
      // this.getTeacherList()
      this.getKcList()
      this.$nextTick(() => {
        this.$refs.memberSearchRef.clearSearch()
        this.$refs.bmForm.clearValidate()
      })
    },
    showAddBtn() {
      this.showAdd = true
      this.xyForm = {}
    },
    // PC预约课程信息
    getreserveClassInfoPC() {
      const param = { ...this.bmForm }
      const arr = [...this.kcList]
      if (param.courseId) {
        this.getTeacherList()
        arr.forEach(s => {
          if (s.courseId === param.courseId) {
            if (s.courseType !== '4') {
              this.pdSj = false
              let memberLength = 0
              if (param.members && param.members.length > 0) {
                memberLength = param.members.length
                let price = ''
                price = (s.price * memberLength).toFixed(2)
                this.$set(this.bmForm, 'price', price)
              } else {
                this.$set(this.bmForm, 'price', '')
              }
            } else {
              this.$set(this.bmForm, 'price', '')
              this.pdSj = true
            }
            this.$refs.bmForm.clearValidate()
          }
        })
      }
      if (!param.courseId || !param.teacherId || !param.day) {
        this.timeList = []
        return
      }
      reserveClassInfoPC({
        param
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.timeList = res.record.timeInfos || []
            arr.forEach(s => {
              if (s.courseId === param.courseId && s.courseType === '4') {
                let memberLength = 0
                let priceb = ''
                if (param.members && param.members.length > 0) {
                  memberLength = param.members.length
                  if (param.time && param.time.length > 0) {
                    priceb = (res.record.price * memberLength * param.time.length).toFixed(2)
                    this.$set(this.bmForm, 'price', priceb)
                    this.$refs.bmForm.clearValidate()
                  }
                }
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    confirmAction() {
      const that = this
      const timeList = [...this.timeList]
      const param = { ...this.bmForm }
      const memberInfo = { ...this.tgMemberInfo }
      memberInfo.remainingMoney = memberInfo.rechargeMoney
      memberInfo.remainingGiveMoney = memberInfo.giveMoney
      const privateCourseTimeInterval = []
      const time = param.time
      this.$refs.bmForm.validate((valid) => {
        if (valid) {
          timeList.forEach((a, index) => {
            time.forEach((b) => {
              if (b === index) {
                privateCourseTimeInterval.push({
                  startPeriodTime: a.startTime,
                  endPeriodTime: a.endTime
                })
              }
            })
          })
          param.privateCourseTimeInterval = privateCourseTimeInterval
          param.phone = memberInfo.phone
          param.userName = memberInfo.nickName
          param.memberInfo = memberInfo
          param.sjFlag = this.pdSj ? '1' : '0'
          param.students = param.members.join()
          this.isShowOrder = true
          this.$nextTick(() => {
            that.$refs.orderRef.continuePay(param, 'studentAdd')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 课程列表
    getKcList() {
      const venueIds = [sessionStorage.getItem('venueId')]
      publishCourseList({ param: { venueIds, channel: '02', flag: '2' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.kcList = res.recordList || []
        })
    },
    // 保存学员
    sideBtn() {
      const param = { ...this.xyForm }
      if (!param.name) {
        this.$message.error('请输入学员姓名')
        return
      }
      if (!param.sex) {
        this.$message.error('请选择性别')
        return
      }
      param.memberId = this.tgMemberInfo.id
      studentAdd({
        param
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.$message.success('添加成功')
            this.showAdd = false
            this.getStuList()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    closeDrawer() {
      this.tgMemberInfo = {}
      this.$refs.memberSearchRef.clearSearch()
      this.$set(this.bmForm, 'memberId', '')
      this.$refs.bmForm.clearValidate()
      this.showApplication = false
    },
    tgMemberClear() {
      this.tgMemberInfo = {}
    },
    tgMemberSelect(item) {
      const fn = () => {
        this.tgMemberInfo = item
        this.getStuList()
        this.$set(this.bmForm, 'memberId', item.id)
        this.$refs.bmForm.clearValidate()
      }
      fn()
    },
    getStuList() {
      studentListByMember({
        param: {
          memberId: this.tgMemberInfo.id
        }
      })
        .then(res => {
          // console.log(res)
          this.members = res.recordList || []
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 教练
    getTeacherList() {
      const venueId = sessionStorage.getItem('venueId')
      const param = { ...this.bmForm }
      teacherGmList({
        param: {
          venueId,
          courseId: param.courseId
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.teachList = res.recordList || []
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

</style>
